/**
 * 
 */
package com.android.calldelay.services;


import java.util.Calendar;

import com.android.calldelay.AppInfo;
import com.android.calldelay.receiver.CallingStateReceiver;
import com.android.calldelay.receiver.OnCallDisconnectReceave;


import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.provider.CallLog;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;

/**
 * @author INVEERA
 *
 */
public class ServiceForCallingStateRecever extends Service {

	private CallLogObserver observer;

	ServiceForCallingStateRecever context;
	private static final String LOG_TAG = "ServiceForCallingStateRecever";

	@Override

	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);

		registerContentObserver();
		Log.d(LOG_TAG, "Service is started");





	}
	private void showToast(String msg) {
		//	Toast.makeText(getApplicationContext(),msg, Toast.LENGTH_SHORT).show();

	}


	private void registerContentObserver() {

		if (observer != null) {
			return;
		}
		observer = new CallLogObserver(new Handler(),
				getApplicationContext());
		getContentResolver().registerContentObserver(
				android.provider.CallLog.Calls.CONTENT_URI, true, observer);
	}
	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getContentResolver().unregisterContentObserver(observer);
		observer = null;
		//showToast("Servece is stoped");


	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}


	public class CallLogObserver extends ContentObserver {


		private Context context;
		private boolean flag = true;
		private long duration;


		public CallLogObserver(Handler handler, Context context) {
			super(handler);
			this.context = context;
		}
		@Override
		public boolean deliverSelfNotifications() {
			return true;
		}

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			Log.i(LOG_TAG, "CallLogs Onhange()");
			Log.d(LOG_TAG, "duration of call is "+AppInfo.CALL_DURATION);

			// making query to get the call log of the last call

			makeCallQuery();


		}


		private void makeCallQuery() {
			try {
				Cursor c = context.getContentResolver().query(
						CallLog.Calls.CONTENT_URI, null, null, null,
						CallLog.Calls.DATE + " DESC");
				if (c != null) {
					if (c.moveToFirst()) {
						int type = Integer.parseInt(c.getString(c
								.getColumnIndex(CallLog.Calls.TYPE)));
						/*
						 * increase call counter for outgoing call only
						 */
						if (type == 2) {
							String number = c.getString(c
									.getColumnIndex(CallLog.Calls.NUMBER));

							duration = c.getLong(c
									.getColumnIndex(CallLog.Calls.DURATION));

							Log.i(LOG_TAG, "numer = " + number + " type = " + type
									+ " duration = " + duration);

						}

						if (duration == 0  ) {
							redial();
						}  else if (duration >0) {
							AppInfo.CALL_DURATION = duration;
							showToast("call is started");
							//setSpeakerOff();

						}
					}
					c.close();
				} else
					Log.e(LOG_TAG, "Call Logs Cursor is Empty");
			} catch (Exception e) {

				Log.e("", "Error on onChange : " + e.toString());
			}

		}
		private void setSpeakerOff() {
			AudioManager audioManager = (AudioManager) context
					.getSystemService(Context.AUDIO_SERVICE);
			audioManager.setMode(AudioManager.MODE_IN_CALL); 
			audioManager.setSpeakerphoneOn(false);

		}

		private void redial() {
			final int dialAttemptsFromPref = context.getSharedPreferences(AppInfo.APP_PREF, 0).getInt(AppInfo.KEY_DIAL_ATTEMPTS_KEY, 0);
			if (dialAttemptsFromPref == 0) {
				//send only message to first number
				//	Toast.makeText(ctx, "send only message to first number", Toast.LENGTH_SHORT).show();
				Log.i(LOG_TAG, "send only message to first number"+dialAttemptsFromPref);
				if (AppInfo.COUNT!=1) {
					sendMessageToFirstNumber("5556");
					AppInfo.COUNT = 1;
				}

				//sendMessage("5556");
			} else { 

				alternativeRedial(dialAttemptsFromPref);
			}

		}

		private void alternativeRedial(int dialAttemptsFromPref) {
			if (AppInfo.DIAL_ATTEMPTS >0) {
				if (dialAttemptsFromPref%2 == 0) {

					if (AppInfo.DIAL_ATTEMPTS % 2 != 0) {
						dialSecondNumber();
						setUpAlarmForDisconnect();
						AppInfo.MESSAGE_COUNTER = 2;
						AppInfo.COUNT =0;


					} else    {

						dialFirstNumber();
						setUpAlarmForDisconnect();
						AppInfo.MESSAGE_COUNTER = 1;
						AppInfo.COUNT =0;

					}  

				}else {

					if (AppInfo.DIAL_ATTEMPTS % 2 != 0) {

						dialFirstNumber();
						setUpAlarmForDisconnect();
						AppInfo.MESSAGE_COUNTER = 1;
						AppInfo.COUNT =0;


					} else{

						dialSecondNumber();
						setUpAlarmForDisconnect();
						AppInfo.MESSAGE_COUNTER = 2;
						AppInfo.COUNT = 0;

					}  

				}


			}else
			{ 

				// code for sending message
				//Toast.makeText(context,"no more dial attempts",  Toast.LENGTH_SHORT).show();
				if (AppInfo.COUNT != 1) {
					if (AppInfo.MESSAGE_COUNTER == 1) {
						sendMessageToFirstNumber("5556");
						AppInfo.COUNT = 1;
					}else if (AppInfo.MESSAGE_COUNTER == 2) {
						sendMessageToSecondNumber("5558");
						AppInfo.COUNT = 1;


					} 

				}

			} 
		}




		private void setUpAlarmForDisconnect() { 


			if (!AppInfo.FLAG_CALL_IS_DISCONNECTED) {
				AlarmManager alarmManager = (AlarmManager) context
						.getSystemService(Context.ALARM_SERVICE);
				Intent intent = new Intent(context,
						OnCallDisconnectReceave.class);
				PendingIntent pendingIntent = PendingIntent.getBroadcast(
						context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
				// retriving the seconds 
				int secondsBeforeDialingAgain = context.getSharedPreferences(
						AppInfo.APP_PREF, 0).getInt(
								AppInfo.KEY_SECONDS_BEFORE_DIALING_AGAIN, 0);
				// Getting current time and add the seconds in it
				Calendar cal = Calendar.getInstance();
				cal.add(Calendar.SECOND, secondsBeforeDialingAgain);
				alarmManager.set(AlarmManager.RTC_WAKEUP,
						cal.getTimeInMillis(), pendingIntent);
			}

		}




		private void sendMessageToSecondNumber(String number) {
			String secondNumber = context.getSharedPreferences(AppInfo.APP_PREF, 0)
					.getString(AppInfo.KEY_SECOND_NUMBER_KEY, "N/A");
			String message = context.getSharedPreferences(AppInfo.APP_PREF, 0)
					.getString(AppInfo.KEY_MESSAGE_TEXT, "Message from Demo auto SmsManager");SmsManager sm = SmsManager.getDefault();
					sm.sendTextMessage(secondNumber, null, message, null, null);
		}

		private void sendMessageToFirstNumber(String number) {
			String firstNumber = context.getSharedPreferences(AppInfo.APP_PREF, 0)
					.getString(AppInfo.KEY_FIRST_NUMBER_KEY, "N/A");
			String message    = context.getSharedPreferences(AppInfo.APP_PREF, 0)
					.getString(AppInfo.KEY_MESSAGE_TEXT, "Message from Demo auto SmsManager");
			SmsManager sm = SmsManager.getDefault();

			sm.sendTextMessage(firstNumber, null, message, null, null);

		}
		/*
		private void sendMessage(String number) {
			SmsManager sm = SmsManager.getDefault();
			String firstNumber = context.getSharedPreferences(AppInfo.APP_PREF, 0)
					.getString(AppInfo.KEY_FIRST_NUMBER_KEY, "N/A");
			String message = context.getSharedPreferences(AppInfo.APP_PREF, 0)
					.getString(AppInfo.KEY_MESSAGE_TEXT, "Message from Demo auto SmsManager");
			sm.sendTextMessage(number, null, message, null, null);

		}
		 */
		private void dialFirstNumber() { 
			if (AppInfo.FLAG_CALL_IS_DISCONNECTED) {

				try{

					String firstNumber = context.getSharedPreferences(AppInfo.APP_PREF, 0)
							.getString(AppInfo.KEY_FIRST_NUMBER_KEY, "N/A");
					if (!firstNumber.equalsIgnoreCase("N/A")) {
						//String mobileNo = "5556";
						String uri = "tel:" + firstNumber.trim();
						Intent intent = new Intent(Intent.ACTION_CALL);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.setData(Uri.parse(uri));

						context.startActivity(intent);
						AppInfo.FLAG_CALL_IS_DISCONNECTED =false;
						Log.d(LOG_TAG, "Call is disconnected "+AppInfo.FLAG_CALL_IS_DISCONNECTED);
						//	showToast("Call is connected"+AppInfo.FLAG_CALL_IS_DISCONNECTED);



					}

				}catch (Exception e) {
					// TODO: handle exception

				}
			}

		}
		private void dialSecondNumber() {


			if (AppInfo.FLAG_CALL_IS_DISCONNECTED) {


				try {
					String secondNumber = context.getSharedPreferences(
							AppInfo.APP_PREF, 0).getString(
									AppInfo.KEY_SECOND_NUMBER_KEY, "N/A");
					if (!secondNumber.equalsIgnoreCase("N/A")) {
						//String mobileNo = "5556";
						String uri = "tel:" + secondNumber.trim();
						Intent intent = new Intent(Intent.ACTION_CALL);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.setData(Uri.parse(uri));
						context.startActivity(intent);
						AppInfo.FLAG_CALL_IS_DISCONNECTED = false;
						Log.d(LOG_TAG, "Call is disconnected "+AppInfo.FLAG_CALL_IS_DISCONNECTED);
						//showToast("Call is connected"+AppInfo.FLAG_CALL_IS_DISCONNECTED);

					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		private void showToast(String msg) {
			Toast.makeText(context,msg, Toast.LENGTH_SHORT).show();
			//getCallLog();
		}
	}

}
